<template>
  <div
    :id="widgetInstanceId"
    ref="tabContainer"
    :class="`tab-container-for-visual ${className}`"
    :style="containerStyle"
  >
    <div
      ref="containerTop"
      class="container-top"
      :style="{ ...getTabPadding(), ...(gridStyle ? gridStyle : {}) }"
    >
      <slot name="container-top">
        <div
          class="container-title"
          :style="getTitleStyle()"
        >
          <slot name="title"></slot>
        </div>
      </slot>
      <div class="container-tabs">
        <slot name="container-tabs">
          <ul ref="tabs">
            <li
              v-for="(tab, index) in tabDataN"
              :key="index"
              :class="{ on: tab.isActived }"
              @click.stop="clickTab(index)"
            >
              <slot
                v-bind="{ tab, index }"
                name="tab"
              >
                <span>{{ tab.label }}</span>
              </slot>
            </li>
          </ul>
        </slot>
      </div>
    </div>
    <div
      :class="{ 'container-conts-wrap': true, }"
      :style="{...getContainerBgColor, ...containerContsWrapStyle}"
    >
      <div
        :class="{
          'container-outline': $parent.$options.name === 'ElasticContainer' ? false : isDesignViewNew || !isXvueEnv
        }"
        :style="getContainerWrapStyle"
      >
        <div
          ref="widgetContainerWrap"
          :class="{ 'container-conts': true }"
          :title="isDesignViewNew ? hoverTip || $demoi18n('tabContainer.wrap.hoverTitle') : ''"
          :style="{ overflow: wrapOverflowStyle || 'unset' }"
        >
          <xvue-wigetContainer
            v-if="isXvueEnv"
            ref="xvueWidgetContainer"
            :is-design-view="isDesignViewNew"
            :widget-instance-id="wcId"
            :w="widgetContainerWidth"
            :h="widgetContainerHeight"
            widget-name="xvue-wigetContainer"
            :parent-id="widgetInstanceId"
            :container-wrap-config="parentConfig"
          ></xvue-wigetContainer>
          <span
            v-if="tip && (isDesignViewNew || !isXvueEnv)"
            :style="tipStyle"
          >{{ tip }}</span>
        </div>
        <div class="switch-btn">
          <slot name="switchBtn"></slot>
        </div>
      </div>
    </div>

    <div class="container-footer" :style="{...getContainerBgColor, ...containerFooterStyle}">
      <slot name="footer"></slot>
    </div>
  </div>
</template>
<script>
import EventBus from '@/event-bus/EventBus.js';
import { getCssStyle, isEmpty } from '@/utils/util';
import { nextTick } from 'vue';
import configData from './config';

export default {
  name: 'XVueTabContainer',
  props: [
    'isDesignView',
    'parentId',
    'widgetId',
    'widgetInstanceId',
    'widgetName',
    'w',
    'h',
    'diyClassName',
    'tabData',
    'activeIndex',
    'tabPadding',
    'fontSize',
    'lineHeight',
    'gridStyle',
    'isFilterContainer',
    'parentConfig',
    'tip',
    'tipStyle',
    'parentProperty',
    'boxWidth',
    'boxHeight',
    'hoverTip',
    'widgetGridStyle',
    'containerStyle',
    'containerContsWrapStyle',
    'containerFooterStyle',
  ],
  emits: [],
  data() {
    return {
      orgConfig: null,
      tabDataN: [],
      widgetContainerWidth: 0,
      widgetContainerHeight: 0,
      setHeightTimer: null,
      wrapOverflowStyle: '',
    };
  },
  computed: {
    isXvueEnv() {
      // 是否在xvue项目环境
      if (window._xvueStore) {
        return true;
      }
      return false;
    },
    isDesignViewNew() {
      if (this.isDesignView === true || this.isDesignView === false) {
        return this.isDesignView;
      }
      return true;
    },
    wcId() {
      // 内部的子container id
      const wcId = `${this.widgetInstanceId}_widgetContainer`;
      return wcId;
    },
    className() {
      return this.diyClassName || 'tab-container-default';
    },
    tabDataLen() {
      return this.tabData.length;
    },
    getContainerWrapStyle() {
      const _style = this.widgetGridStyle || {};
      delete _style.backgroundColor;
      const ret = {};
      Object.keys(_style).forEach(key => {
        const _key = key.replace('padding', 'margin');
        ret[_key] = _style[key];
      });
      return { ...ret, ...this.gridStyle, width: '100%', height: '100%' };
    },
    getContainerBgColor() {
      const _style = this.widgetGridStyle || {};
      const { backgroundColor } = _style;
      return { backgroundColor };
    },
  },
  watch: {
    activeIndex() {
      this.sendBus();
      this.resetWidgetContainerSize();
    },
    tabDataLen() {
      this.sendBus();
    },
    w() {
      this.resetWidgetContainerSize();
    },
    h() {
      this.resetWidgetContainerSize();
    },
    boxWidth() {
      this.resetWidgetContainerSize();
    },
    boxHeight() {
      this.resetWidgetContainerSize();
    },
  },
  created() {
    const orgConfig = configData;
    this.orgConfig = JSON.parse(JSON.stringify(orgConfig));
  },
  mounted() {
    if (!this.tabData || this.tabData.length === 0) {
      this.tabDataN = this.orgConfig.propertyConfig.tabData;
    } else {
      this.tabDataN = this.tabData;
    }
    this.initActivedTabClick();
    nextTick(() => {
      this.resetWidgetContainerSize();
    });
  },
  beforeUnmount() {
    clearTimeout(this.setHeightTimer);
  },
  methods: {
    getTabPadding() {
      const pName = this.$parent.$options.name;

      let tabPadding = 40;
      if (pName === 'SimpleTabContainer' || pName === 'FlowTabContainerDiy') {
        tabPadding = 10;
      }
      if (this.tabPadding !== undefined) {
        tabPadding = this.tabPadding;
      }

      let style = {};
      if (pName === 'SimpleTabContainer') {
        const lineHeight = this.lineHeight !== undefined ? this.lineHeight : 26;
        style = {
          paddingBottom: tabPadding,
          lineHeight: lineHeight,
        };
      }
      if (pName === 'FlowTabContainerDiy') {
        style = {
          paddingBottom: tabPadding,
        };
      }
      if (pName === 'FlowTabContainer') {
        style = {

          // height: 135 + tabPadding,
          paddingBottom: tabPadding,
        };
      }

      return getCssStyle(style);
    },

    getTitleStyle() {
      const pName = this.$parent.$options.name;
      const style = {};

      let fontSize = 16;
      if (pName === 'SimpleTabContainer') {
        fontSize = this.fontSize || 18;
      }
      style.fontSize = fontSize;

      if (pName === 'FlowTabContainer') {
        style.paddingBottom = 10;
      }
      return getCssStyle(style);
    },

    clickTab(index) {
      for (let i = 0; i < this.tabDataN.length; i++) {
        if (i === index) {
          this.tabDataN[i].isActived = true;
        } else {
          this.tabDataN[i].isActived = false;
        }
      }
      this.sendBus();
    },

    /*
     * 加载完后点击点击要高亮显示的tab
     * 初始化tab选中状态
     */
    initActivedTabClick() {
      if (this.activeIndex !== -1) {
        setTimeout(this.sendBus, 500);
      }
    },
    sendBus() {
      const { wcId } = this;
      let wcIdTab = `${wcId}_${this.activeIndex}`;
      if (this.tabData) {
        const tabItem = this.tabData[this.activeIndex];
        if (tabItem && !isEmpty(tabItem.tabId)) {
          wcIdTab = `${wcId}_${tabItem.tabId}`;
        }
      }
      EventBus.$emit(`widget-container-instance-changed-${wcId}`, wcIdTab);
    },
    setXvueWidgetBgColor(color) {
      let xvueWidgetContainer = this.$refs['xvueWidgetContainer'];
      if (!xvueWidgetContainer) {
        return;
      }
      xvueWidgetContainer = xvueWidgetContainer['$el'];
      xvueWidgetContainer.style.backgroundColor = color;
    },
    resetWidgetContainerSize() {
      const headerEl = this.$refs['containerTop'];
      let headerH = headerEl.clientHeight;

      const pName = this.$parent.$options.name;

      // 弹性容器
      if (pName === 'ElasticContainer') {
        this.widgetContainerWidth = this.boxWidth;
        this.widgetContainerHeight = this.boxHeight;
        let xvueWidgetContainer = this.$refs['xvueWidgetContainer'];
        if (xvueWidgetContainer) {
          xvueWidgetContainer = xvueWidgetContainer['$el'];
          xvueWidgetContainer.style.border = 'none';
          xvueWidgetContainer.style.transition = 'all .35s';
          xvueWidgetContainer.style.animation = 'waverForTabContainer 1.5s linear infinite';
          setTimeout(()=>{
            xvueWidgetContainer.style.height = `${this.boxHeight}px`;
            xvueWidgetContainer.style.width = `${this.boxWidth}px`;
          }, 600);
        }
        const { overflowXSetting } = this.parentProperty || {};
        this.wrapOverflowStyle = overflowXSetting === 'slider' ? 'auto' : 'hidden';
        return;
      } else {
        this.wrapOverflowStyle = null;
      }

      // 灯笼链路页签-定制
      if (pName === 'FlowTabContainer') {
        const titleH = headerEl.querySelector('.container-title').clientHeight;
        const tabsH = headerEl.querySelector('.container-tabs').clientHeight;
        headerH = titleH + tabsH + 12;
        headerEl.style.height = `${headerH}px`;
      }
      if (pName === 'FilterContainer') {
        this.widgetContainerHeight = '100%';
        this.widgetContainerWidth = '100%';
      }
      nextTick(() => {
        const boxInfo = this.$refs.widgetContainerWrap.getBoundingClientRect();
        this.widgetContainerHeight = boxInfo.height;
        this.widgetContainerWidth = boxInfo.width;
      });
    },
  },
};
</script>
<style lang="less">
.tab-container-default {
  display: flex;
  flex-direction: column;
  height: 100%;
  .container-title {
    display: block;
    font-size: 16px;
    margin: 10px;
  }
  .container-tabs {
    display: flex;
    justify-content: flex-end;
    ul {
      line-height: 20px;
      padding-right: 20px;
      li {
        float: left;
        border: 1px solid #aaa;
        margin-left: 10px;
        padding: 5px 10px;
        background-color: #eaeaea;
        cursor: pointer;
        span {
          font-size: 14px;
        }
      }
    }
  }
  .container-conts {
    margin-top: 10px;
    background-color: #defff5;
    flex: 1;
    min-height: 0;
  }
}

/* tab容器公共样式 */
.tab-container-for-visual {
  display: flex;
  height: 100%;
  overflow: hidden;
  flex-direction: column;
  .container-top {
    flex-shrink: 0;
  }
  .container-conts-wrap {
    display: flex;
    flex: 1;
    min-height: 0;
    height: 0;
    overflow: hidden;
    .container-conts {
      height: 100%;
      overflow: hidden;
      .light {
        > .el-loading-mask {
          background-color: hsla(0, 0%, 100%, 0.9);
        }
      }
      .dark {
        > .el-loading-mask {
          background-color: rgba(0, 0, 0, 0.72);
        }
      }
    }
  }
  .container-outline {
    flex: 1;
    border: none;
    outline: 1px solid lightskyblue;
    transition: all 0.35s;
    animation: waverForTabContainer 1.5s infinite linear;
    position: relative;
    margin: 1px;
  }
}
</style>
